<template>
  <div>
    <!-- Floating Button -->
    <div
        class="floating-button draggable"
        :style="{ top: buttonTop + 'px', left: buttonLeft + 'px' }"
        @mousedown="onButtonDragStart"
        @click="toggleChat"
    ></div>

    <!-- Chat Dialog -->
    <div
        v-if="isChatOpen"
        class="chat-dialog"
        :class="{ expanded: isExpanded }"
        :style="dialogPosition"
    >
      <div class="chat-header">
        <span>AI助手</span>
        <div class="control-buttons">
          <el-button style="background-color: transparent; border: none; color: #fff;" @click="toggleChat" title="最小化" icon="el-icon-minus"></el-button>
          <el-button style="background-color: transparent; border: none; color: #fff;" @click="toggleExpand" title="最大化" icon="el-icon-full-screen"></el-button>
          <el-button style="background-color: transparent; border: none; color: #fff;" @click="closeChat" title="关闭" icon="el-icon-close"></el-button>
        </div>
      </div>
      <div class="chat-content">
        <!-- Welcome Message -->
        <div v-if="chatHistory.length === 0" class="welcome-message">
          欢迎使用 AI 助手！请在下方输入框中向我提问。
        </div>

        <!-- Chat History -->
        <div v-for="(message, index) in chatHistory" :key="index" class="message-container">
          <div :class="['message-box', message.isUser ? 'user-box' : 'ai-box']">
            <div v-for="(line, lineIndex) in message.text.split('\n')" :key="lineIndex">
              <p>{{ line }}</p>
            </div>
          </div>
        </div>

        <!-- Loading Indicator -->
        <div v-if="loading" class="loading-indicator">
          <p>稍等...</p>
          <div class="spinner"></div>
        </div>
      </div>

      <div class="chat-input">
        <textarea
            v-model="userInput"
            @input="adjustTextareaHeight"
            @keydown="handleKeydown"
            placeholder="向AI助手提问..."
            rows="1"
            class="input-box"
        ></textarea>
        <button @click="sendMessage" class="send-btn-icon">
          <i class="el-icon-top"></i>
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { sendChatQuestion, getChatAnswer } from "@/api"; // Import your API functions

export default {
  name: "FloatingAiAssistant",
  data() {
    return {
      isChatOpen: false,
      isExpanded: false,
      chatHistory: [],
      userInput: "",
      buttonTop: 100,
      buttonLeft: 100,
      dragging: false,
      dragOffset: { x: 0, y: 0 },
      loading: false, // Loading state
    };
  },
  computed: {
    dialogPosition() {
      const dialogHeight = this.isExpanded ? "90%" : "500px";
      const dialogWidth = this.isExpanded ? "90%" : "450px";

      const topOffset = this.buttonTop - 510;
      const bottomOffset = this.buttonTop + 70;
      const rightOffset = this.buttonLeft + 450;
      const windowHeight = window.innerHeight;
      const windowWidth = window.innerWidth;

      let top = topOffset;
      let left = this.buttonLeft;
      if (top < 0) {
        top = bottomOffset;
      }

      if (rightOffset > windowWidth) {
        left = windowWidth - 460;
      }

      return {
        top: this.isExpanded ? "5%" : `${top}px`,
        left: this.isExpanded ? "5%" : `${left}px`,
        height: dialogHeight,
        width: dialogWidth,
      };
    },
  },
  methods: {
    toggleChat() {
      this.isChatOpen = !this.isChatOpen;
    },
    toggleExpand() {
      this.isExpanded = !this.isExpanded;
    },
    closeChat() {
      this.isChatOpen = false;
      this.isExpanded = false;
    },
    onButtonDragStart(event) {
      this.dragging = true;
      this.dragOffset.x = event.clientX - event.target.getBoundingClientRect().left;
      this.dragOffset.y = event.clientY - event.target.getBoundingClientRect().top;
      document.addEventListener("mousemove", this.onButtonDrag);
      document.addEventListener("mouseup", this.onButtonDragEnd);
    },
    onButtonDrag(event) {
      if (!this.dragging) return;
      this.buttonLeft = Math.max(0, event.clientX - this.dragOffset.x);
      this.buttonTop = Math.max(0, event.clientY - this.dragOffset.y);
    },
    onButtonDragEnd() {
      this.dragging = false;
      document.removeEventListener("mousemove", this.onButtonDrag);
      document.removeEventListener("mouseup", this.onButtonDragEnd);
    },
    adjustTextareaHeight(event) {
      const textarea = event.target;
      textarea.style.height = "auto";
      textarea.style.height = `${textarea.scrollHeight}px`;
    },
    handleKeydown(event) {
      if (event.key === "Enter" && !event.shiftKey) {
        event.preventDefault(); // 阻止默认换行行为
        this.sendMessage(); // 调用发送消息的方法
      }
    },
    async sendMessage() {
      if (this.loading || !this.userInput.trim()) return; // 防止重复发送
      this.loading = true;

      const question = this.userInput.trim();
      this.chatHistory.push({ text: question, isUser: true });
      this.userInput = "";
      this.loading = true;

      try {
        await sendChatQuestion(question);
        const answer = await getChatAnswer();
        this.chatHistory.push({ text: answer, isUser: false });
      } catch (error) {
        console.error("AI助手请求失败:", error);
        this.chatHistory.push({ text: "AI助手暂时不可用，请稍后重试。", isUser: false });
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>

<style scoped>
.floating-button {
  position: fixed;
  width: 70px;
  height: 70px;
  background-image: url("@/assets/chat_icon.png");
  background-size: cover;
  background-position: center;
  border-radius: 50%;
  cursor: pointer;
  z-index: 1000;
}

.chat-dialog {
  position: fixed;
  background-color: white;
  border: 1px solid #ddd;
  border-radius: 10px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
}

.chat-header {
  background: linear-gradient(90deg, #8E6DD7 ,#61B7CF);
  color: white;
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

.chat-content {
  flex:1;
  background-color: #ffffff; /* 纯白背景 */
  padding: 20px;
  overflow-y: auto;
  border-radius: 10px;
}

.message-container {
  margin-bottom: 10px;
}

.message-box {
  padding: 10px;
  border-radius: 8px;
  max-width: 80%;
  word-break: break-word;
  opacity: 0;
  transform: translateY(10px);
  animation: fadeIn 0.3s ease forwards;
}
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 用户消息样式 */
.user-box {
  background-color: #e8f4ff; /* 高级浅蓝背景 */
  color: #333333; /* 深灰色字体 */
  border-left: 4px solid #007bff;
  padding: 15px 20px;
  margin: 10px 0;
  border-radius: 10px; /* 圆角设计 */
  font-family: "Arial", sans-serif; /* 简约字体 */
  font-size: 14px; /* 字体大小 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 轻微阴影 */
  line-height: 1.6; /* 行间距 */
  word-break: break-word;
  max-width: 80%; /* 最大宽度 */
  text-align: left; /* 文本左对齐 */
  margin-left: auto; /* 靠右对齐 */
}

/* AI助手消息样式 */
.ai-box {
  background-color: #f9f9f9; /* 高级浅灰背景 */
  color: #333333; /* 深灰色字体，优雅且易读 */
  border-right: 4px solid #007bff; /* 左侧蓝色标记条，增强视觉 */
  padding: 15px 20px;
  margin: 10px 0;
  border-radius: 10px; /* 圆角设计，现代感 */
  font-family: "Arial", sans-serif; /* 简约字体 */
  font-size: 16px; /* 更大更清晰的字体 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 添加轻微阴影 */
  line-height: 1.6; /* 增加行间距，提升阅读体验 */
  word-break: break-word; /* 长词换行 */
  max-width: 80%; /* 限制最大宽度 */
  text-align: left; /* 文本左对齐 */
}

.welcome-message {
  color: #666666; /* 浅灰色提示文本 */
  font-size: 14px; /* 较小字体 */
  text-align: center;
  margin-bottom: 20px;
  font-family: "Arial", sans-serif;
}

.loading-indicator {
  text-align: center;
  margin: 10px 0;
}

.spinner {
  margin: 5px auto;
  width: 24px;
  height: 24px;
  border: 4px solid #007bff;
  border-top-color: transparent;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.chat-input {
  display: flex; /* 使用 Flexbox 布局 */
  padding: 8px; /* 内边距 */
  background-color: #fff;
  align-items: flex-end ; /* 垂直居中对齐 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 添加阴影，增加层次感 */
  margin: 6px 6px; /* 上下间距 */
}

.input-box {
  flex: 1; /* 输入框填满剩余空间 */
  resize: none; /* 禁止用户调整输入框大小 */
  padding: 8px 12px; /* 输入框内边距 */
  outline: none; /* 去掉输入框选中时的外框 */
  font-size: 15px; /* 字体大小 */
  line-height: 1.5; /* 行高 */
  color: #333; /* 字体颜色 */
  background-color: transparent; /* 保持背景透明，与容器一致 */
  height: 26px; /* 调整输入框高度 */
  border: 2px solid #ddd; /* 浅灰边框 */
  border-radius: 2px; /* 圆角 */
}

/* 发送按钮样式 */
.send-btn-icon {
  width: 40px; /* 按钮宽度 */
  height: 40px; /* 按钮高度 */
  background-color: #007bff; /* 按钮背景颜色 */
  border: none;
  border-radius: 50%; /* 圆形按钮 */
  display: flex;
  align-items: center; /* 图标垂直居中 */
  justify-content: center; /* 图标水平居中 */
  cursor: pointer;
  margin-left: 10px; /* 按钮与输入框的间距 */
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); /* 按钮阴影 */
  transition: all 0.3s ease;
}

/* 鼠标悬停效果 */
.send-btn-icon:hover {
  background-color: #0056b3; /* 悬停时背景颜色 */
  transform: scale(1.05); /* 悬停时轻微放大 */
}

.send-btn-icon .el-icon-top {
  font-size: 16px; /* 图标大小 */
  color: #ffffff; /* 图标颜色 */
}

/* 鼠标悬停时图标颜色变化 */
.send-btn-icon:hover .el-icon-top {
  color: #f0f0f0; /* 悬停时图标颜色 */
}
</style>
